package com.walle.service.user;

import com.walle.core.constants.Constants;
import com.walle.core.utils.Utils;
import com.walle.dao.user.UserMapper;
import com.walle.dao.user.model.User;
import com.walle.dao.user.model.UserBind;
import com.walle.service.BaseService;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService extends BaseService<User, UserMapper> {

    @Resource
    private UserBindService userBindService;

    public UserService(UserMapper mapper, Environment environment) {
        super(mapper, environment);
    }

    /**
     * 根据手机号码查询
     *
     * @param bindType 绑定类型
     * @param value 绑定值
     * @return User
     */
    public User findByBindType (String bindType, String value) {
        UserBind queryDto = new UserBind();
        queryDto.setBindType(bindType);
        queryDto.setBindValueCipher(Utils.Secure.encryptField(value));
        queryDto.setDeleted(Boolean.FALSE);
        UserBind userBind = userBindService.findFirst(queryDto);
        if (userBind == null) {
            return null;
        }
        return this.findById(userBind.getUserId());
    }

    /**
     * 绑定手机号码
     *
     * @param userId 用户ID
     * @param phoneNumber 手机号码
     */
    public Integer bindPhoneNumber (Integer userId, String phoneNumber) {
        UserBind newBind = new UserBind();
        newBind.setUserId(userId);
        newBind.setBindType(Constants.User.BIND_TYPE_PHONE_NUMBER);
        newBind.setBindValueDigest(Utils.Digest.digestMobile(phoneNumber));
        newBind.setBindValueCipher(Utils.Secure.encryptField(phoneNumber));
        return userBindService.create(newBind);
    }
}
